package com.situ.mall.controller;

import com.situ.mall.pojo.Category;
import com.situ.mall.pojo.Product;
import com.situ.mall.pojo.vo.CategoryIndexVO;
import com.situ.mall.pojo.vo.ProductVO;
import com.situ.mall.service.ICategoryService;
import com.situ.mall.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    @Autowired
    private ICategoryService categoryService;

//    @Autowired
//    private RedisTemplate redisTemplate;

    @Autowired
    private IProductService productService;

    private Map<String, Object> map = new HashMap<>();

    @RequestMapping("/")
    public String index(Model model) {
        System.out.println("IndexController.index");
        List<Category> topCategoryList = categoryService.selectTopCategoryList();;
        List<Category> secondCategoryList = categoryService.selectSecondCategoryList();
        List<CategoryIndexVO> topCategoryVO = new ArrayList<>();
        for (Category category : topCategoryList) {
            CategoryIndexVO categoryIndexVO = new CategoryIndexVO();
            categoryIndexVO.setId(category.getId());
            categoryIndexVO.setName(category.getName());
            categoryIndexVO.setDeleted(category.getDeleted());
            categoryIndexVO.setGmtCreate(category.getGmtCreate());
            categoryIndexVO.setGmtModified(category.getGmtModified());
            categoryIndexVO.setParentId(category.getParentId());
            categoryIndexVO.setStatus(category.getStatus());
            categoryIndexVO.setProducts(productService.selectAll(category.getId()));
            topCategoryVO.add(categoryIndexVO);
        }
        model.addAttribute("topCategoryList", topCategoryVO);
        model.addAttribute("secondCategoryList", secondCategoryList);
        return "index";
    }

    @RequestMapping("/index1")
    public String index1(Model model) {
        System.out.println("IndexController.index");
        List<Category> topCategoryList = (List<Category>) map.get("topCategoryList");
        if (CollectionUtils.isEmpty(topCategoryList)) {
            topCategoryList = categoryService.selectTopCategoryList();
            map.put("topCategoryList", topCategoryList);
        }
//        List<Category> topCategoryList = categoryService.selectTopCategoryList();
        List<Category> secondCategoryList = categoryService.selectSecondCategoryList();
        model.addAttribute("topCategoryList", topCategoryList);
        model.addAttribute("secondCategoryList", secondCategoryList);
        return "index";
    }
}
